package chapter3;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * Created by qpx on 2018/5/12.
 */
public class DeadLockChecker {
    private static ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true){
                long[] deadlockedThreads = mxBean.findDeadlockedThreads();
                if (deadlockedThreads!=null){
                    ThreadInfo[] threadInfo = mxBean.getThreadInfo(deadlockedThreads);
                    for (Thread t:Thread.getAllStackTraces().keySet()){
                        for (int i =0;i<threadInfo.length;i++){
                            if (t.getId()==threadInfo[i].getThreadId()){
                                t.interrupt();
                            }
                        }
                    }
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    public static void checked(){

        Thread thread = new Thread(runnable);
        thread.setDaemon(true);
        thread.start();
    }
}
